﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.DataContract;

namespace ActivitySystem.Web
{
    public class PageListMaintainer
    {
        public void Run()
        {
            try
            {
                RefreshPageList();
            }
            catch (Exception e)
            {
                Log log = new Log();
                log.Level = LogLevel.Error.ToString();
                log.Source = typeof(PageListMaintainer).Name;
                log.Data = e.ToString();

                Logger.Write(log);
            }
        }

        #region Private Method

        private void RefreshPageList()
        {
            PageManager pageManager = new PageManager();

            Dictionary<string, Page> pageFiles = GetAllWebPages();
            var pages = pageManager.SelectAll();

            var unavailablePages = new Collection<Page>();
            var newAddedPages = new Collection<Page>();

            foreach (var page in pages)
            {
                int index = page.Url.IndexOf('?');
                string pageUrl = index == -1 ? page.Url.Trim() : page.Url.Substring(0, index).Trim();
                if (!pageFiles.ContainsKey(pageUrl.ToLower()))
                {
                    unavailablePages.Add(page);
                }
            }

            foreach (string pageFile in pageFiles.Keys)
            {
                bool flag = false;
                foreach (var page in pages)
                {
                    if (page.Url.ToLower().Contains(pageFile))
                    {
                        flag = true;
                        break;
                    }
                }

                if (!flag) newAddedPages.Add(pageFiles[pageFile]);
            }

            // Set isactive to false for not existing pages.
            DisableUnavailablePages(unavailablePages);

            // Create page record in database for new added pages.
            AddNewPages(newAddedPages);
        }

        private Dictionary<string, Sunyi.Project.WebPoint.DataContract.Page> GetAllWebPages()
        {
            var pageFiles = new Dictionary<string, Sunyi.Project.WebPoint.DataContract.Page>();

            if (Directory.Exists(EnvironmentSetting.WebSiteRootPath))
            {
                string[] files = Directory.GetFiles(EnvironmentSetting.WebSiteRootPath, "*.aspx", SearchOption.AllDirectories);

                if (files != null)
                {
                    foreach (string file in files)
                    {
                        string pageName = Path.GetFileNameWithoutExtension(file);
                        string pageUrl = "/" + file.Replace(EnvironmentSetting.WebSiteRootPath, string.Empty).Replace("\\", "/");

                        var page = new Sunyi.Project.WebPoint.DataContract.Page();
                        page.PageName = pageName;
                        page.Url = pageUrl;
                        page.Category = string.Empty;
                        page.NavigationOrder = 0;
                        page.NavigationType = NavigationType.Hidden.ToString();
                        page.IsActive = true;

                        pageFiles.Add(pageUrl.ToLower(), page);
                    }
                }
            }

            return pageFiles;
        }

        private void DisableUnavailablePages(Collection<Sunyi.Project.WebPoint.DataContract.Page> pages)
        {
            PageManager pageManager = new PageManager();

            foreach (var page in pages)
            {
                page.IsActive = false;
                pageManager.Update(page);
            }
        }

        private void AddNewPages(Collection<Sunyi.Project.WebPoint.DataContract.Page> pages)
        {
            PageManager pageManager = new PageManager();

            foreach (var page in pages)
            {
                pageManager.Insert(page);
            }
        }

        #endregion
    }
}